package org.itboys.mobile.service.mysql.web;

import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieWalletBlockRecordMapper;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieWalletBlock;
import org.itboys.mobile.entity.mysql.TianJieWalletBlockRecord;
import org.itboys.mobile.entity.mysql.TianJieWalletRecord;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_区块链_钱包_service
 */
@Service
public class TianJieWalletBlockService extends BaseMySqlService<TianJieWalletBlock> {
    @Autowired
    private TianJieWalletBlockRecordMapper walletBlockRecordMapper;
    @Autowired
    private TianJieMemberService memberService;
    /**
     * 获取消费交易记录
     * @param request
     * @param status。1,待成交，2已成交
     * @return
     */
    public PageResult<TianJieWalletBlockRecord> selectTradeRecord(HttpServletRequest request, Integer status){
        Map<String,Object> param = ParamUtil.packageMongoExactParam(request,"type");
        if(status!=null){
            param.put("status",status);
        }

        //默认只获取买入卖出记录
        param.put("types", Arrays.asList(SundayCommonConstants.block_record_type_buy,SundayCommonConstants.block_record_type_sale));
        List<TianJieWalletBlockRecord> result = walletBlockRecordMapper.select(param);
        //匹配用户信息
        List<Long> memberIds = new ArrayList<>();
        for(TianJieWalletBlockRecord walletBlockRecord:result){
            memberIds.add(walletBlockRecord.getMemberId());
        }
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            param.put("id in",memberIds);
            List<TianJieMember> members = memberService.list(param);
            for(TianJieWalletBlockRecord walletBlockRecord:result){
                for(TianJieMember member:members){
                    if(LongUtil.isNotZreo(walletBlockRecord.getMemberId())&&
                            walletBlockRecord.getMemberId().longValue()==member.getId()){
                            walletBlockRecord.setMemberName(member.getNickName());
                            walletBlockRecord.setMemberMobile(member.getUserName());
                        break;
                    }

                }
            }
        }
        Serializable count =walletBlockRecordMapper.count(param);
        return new PageResult<TianJieWalletBlockRecord>(result,count==null?0:Long.valueOf(count.toString()));
    }
    /**
     * 获取消费交易记录(按会员)
     * @param request
     * @param memberId。
     * @return
     */
    public PageResult<TianJieWalletBlockRecord> selectMemberRecord(HttpServletRequest request, Long memberId){
        Map<String,Object> param =ParamUtil.packageMysqlPageParam(request,"");
        param.put("memberId",memberId);
        List<TianJieWalletBlockRecord> result = walletBlockRecordMapper.select(param);
        Serializable count =walletBlockRecordMapper.count(param);
        //匹配用户信息
        List<Long> memberIds = new ArrayList<>();
        for(TianJieWalletBlockRecord walletBlockRecord:result){
            memberIds.add(walletBlockRecord.getMemberId());
        }
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            param.put("id in",memberIds);
            List<TianJieMember> members = memberService.list(param);
            for(TianJieWalletBlockRecord walletBlockRecord:result){
                for(TianJieMember member:members){
                    if(LongUtil.isNotZreo(walletBlockRecord.getMemberId())&&
                            walletBlockRecord.getMemberId().longValue()==member.getId()){
                        walletBlockRecord.setMemberName(member.getNickName());
                        walletBlockRecord.setMemberMobile(member.getUserName());
                        break;
                    }

                }
            }
        }

        return new PageResult<TianJieWalletBlockRecord>(result,count==null?0:Long.valueOf(count.toString()));
    }

    /**
     * 确认买入卖出交易
     * @param walletBlockRecordIds
     */
    @Transactional
    public void trade_confirm(List<Long> walletBlockRecordIds){
        Long loginUserId = AdminSessionHolder.getAdminUserId();
        if(!LongUtil.isNotZreo(loginUserId)){
            throw new ErrorException("登录信息已失效，请重新登陆");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("ids",walletBlockRecordIds);
        List<TianJieWalletBlockRecord> records = walletBlockRecordMapper.select(param);
        boolean isStatusError=false;
        for(TianJieWalletBlockRecord record:records){
            if(record.getStatus()!=SundayCommonConstants.block_record_status_doing){
                isStatusError=true;
            }

        }
        if(isStatusError){
            throw new ErrorException("记录状态错误，请刷新后重试。");
        }
        for(TianJieWalletBlockRecord record:records){
            record.setStatus( SundayCommonConstants.block_record_status_done);
            walletBlockRecordMapper.update(record);
        }

    }

    /**
     * 修改钱包_区块链（当前只修改卖出天数）
     * @param memberIds
     * @param saleDay
     */
    @Transactional
    public void update_wallet_block(List<Long> memberIds, Integer saleDay) {
        Long loginUserId = AdminSessionHolder.getAdminUserId();
        if (!LongUtil.isNotZreo(loginUserId)) {
            throw new ErrorException("登录信息已失效，请重新登陆");
        }
        if(ListUtil.isNull(memberIds))return;
        //使用用户ID查询钱包，兼容重复用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberIds",memberIds);
        List<TianJieWalletBlock> walletBlocks = super.select(param);
        for(TianJieWalletBlock walletBlock:walletBlocks){
            walletBlock.setSaleDay(saleDay);
            super.update(walletBlock);
        }
    }



}




